package com.buho29.rcmanager;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.ViewGroup;
import android.widget.TextView;

import com.buho29.rcmanager.bd.DatabaseAdapter;
import com.buho29.rcmanager.bd.TableDrive;
import com.buho29.rcmanager.bd.TableModel;
import com.buho29.rcmanager.bd.TablePowerItem;
import com.buho29.rcmanager.bd.TableStatistic;
import com.buho29.rcmanager.utils.Make;
import com.buho29.rcmanager.utils.Format;
import com.buho29.rcmanager.widget.Graph;

public class PowerItemView extends Activity {

	private TextView mResultText;
	private TextView mResultText1;
    
    private Long mId;
	private int mCmd;
	
    public static final String CMD="cmd";
    
	private DatabaseAdapter mDbAdapter;
	private TableDrive mDbTableDrive = new TableDrive();
	private TablePowerItem mDbTablePowerItem = new TablePowerItem();
	private TableStatistic mDbTableStatistic = new TableStatistic();
	
    private Graph mGraphView;
	
    private static final int colors[] = new int[] {
		Color.MAGENTA, Color.BLUE, 
		Color.GREEN, Color.YELLOW,
		Color.CYAN, Color.RED,
		Color.GRAY
	};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDbAdapter = DatabaseAdapter.getInstance(this); 
        mDbTableDrive.setSQLiteDatabase(mDbAdapter.getDatabase());
        mDbTablePowerItem.setSQLiteDatabase(mDbAdapter.getDatabase());
        mDbTableStatistic.setSQLiteDatabase(mDbAdapter.getDatabase());
        
        Bundle extras = getIntent().getExtras();            
		if(savedInstanceState != null){
			mCmd = savedInstanceState.getInt(CMD);
	       	mId = savedInstanceState.getLong(TablePowerItem.COL_ROW_ID);
		}else if(extras != null){
			mCmd = extras.getInt(CMD);
			mId = extras.getLong(TablePowerItem.COL_ROW_ID);
		}
		
		if(mCmd <1) {
			finish();
			return;
		}
		
        setContentView(R.layout.lipo_statistic);

        mResultText = (TextView) findViewById(R.id.tv);
        mResultText1 = (TextView) findViewById(R.id.tv1);
        
        populateFields();
    }   
    
    private void populateFields() {
    	
    	mDbTablePowerItem.setId(mId);
    	mDbTablePowerItem.load();
        
    	
    	mDbTableStatistic.loadPowerItem(mId);  
        
        if(mDbTableStatistic.getCount()<1){
        	Make.toast(this,getText(R.string.helpEmptyFly)).show();
        	setResult(RESULT_CANCELED);
        	finish();
        	return;
        }
        
        
        Cursor models = mDbTableDrive.fetchModels(mId);

        int c = models.getCount();
        
        long modelID[] = new long[c];
        Cursor drives[] = new Cursor[c];
        
        for (int i = 0; i < c; i++) {
        	models.moveToPosition(i);
        	
        	modelID[i] = models.getLong(models.getColumnIndex(TableDrive.COL_MODEL_ID));
        	drives[i] = mDbTableDrive.fetchPower(mId,modelID[i]);
			
		}
        
        models.close();
        
        SpannableStringBuilder r = buildResult1(new SpannableStringBuilder(),
        		mDbTableStatistic.getTotal(),mDbTableStatistic.getCount(),
        		mDbTableStatistic.getAverage(),mDbTableStatistic.getMin(),
        		mDbTableStatistic.getMax(),mDbTablePowerItem.getDate(),Make.NEWLINE
        );//
        mResultText.setText(r);
        mResultText.setMovementMethod(LinkMovementMethod.getInstance());
        
        r = buildDetalledResult(modelID);
        mResultText1.setText(r);
        mResultText1.setMovementMethod(LinkMovementMethod.getInstance());
        
        setTitle(mDbTablePowerItem.getName());
        
        mGraphView = new Graph(this, drives,TableDrive.COL_TIME,colors);
        ViewGroup row = (ViewGroup) findViewById(R.id.layout);
        row.addView(mGraphView,ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
        
        /**/
            
    }
    
	private SpannableStringBuilder buildDetalledResult(long[] modelID) {
        final SpannableStringBuilder ss = new SpannableStringBuilder();

        for (int i = 0; i < modelID.length; i++) {
        	
			long modelId = modelID[i];
			
			
			TableModel tm = new TableModel();
			tm.setSQLiteDatabase(mDbAdapter.getDatabase());
			tm.setId(modelId);
			
			String name = "no found";
			if(tm.load()){
				name = tm.getName();
			}
			
			Make.appendResult(ss, name, "", Make.NEWLINE,i<colors.length ? colors[i] : Color.WHITE);
			
			mDbTableStatistic.loadPower(mId,modelId);
			
	    	int count = mDbTableStatistic.getCount();
	    	int average = mDbTableStatistic.getAverage();
	    	int total = mDbTableStatistic.getTotal();
	    	int max = mDbTableStatistic.getMax();
	    	int min = mDbTableStatistic.getMin(); 
			
			
			buildResult(ss, total, count, average, min, max, Make.SEP);
			
			ss.append(Make.NEWLINE);
		}
     
        return ss;
    }
	
	private SpannableStringBuilder buildResult(SpannableStringBuilder ss, int total,int fly, int average, int min , int max, String sep) {
        
		String[] fields = new String[]{
				(String)getText(R.string.total) ,
				(String)getText(R.string.drive) ,
				(String)getText(R.string.average) ,
				(String)getText(R.string.min) ,
				(String)getText(R.string.max)
		};
		
		Object[] value = new Object[]{
				Format.formatSecondsToString(total),
				fly,
				Format.formatSecondsToString(average),
				Format.formatSecondsToString(min),
				Format.formatSecondsToString(max)
		};
        Make.buildResult(ss, fields, value, sep);
     
        return ss;
    }

    private SpannableStringBuilder buildResult1(SpannableStringBuilder ss, int total,int fly, int average, int min , int max, long date,String sep) {
        
    	buildResult(ss, total, fly, average, min, max, sep);
        // date
    	ss.append(Make.NEWLINE);
        Make.appendResult (ss,getText(R.string.created) , Format.formatDateToString(date),sep);
     
        return ss;
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TablePowerItem.COL_ROW_ID, mId);
        outState.putInt(CMD, mCmd);
    }
    
}
